<template>
	<view class="addbank-container">
		<u-popup :show="addstatus" bgColor="transparent" mode="center" @close="closemodal">
			<view class="delet-modal">
				<view class="delet-modal-image">
				</view>
				<view class="delet-modal-title">
					绑定成功
				</view>
				<view class="delet-modal-tips">
					银行卡已绑定
				</view>
				<view class="delet-modal-btngroup">
					<!-- <view class="delet-modal-cancelbtn" @tap.stop="closemodal">
						取消
					</view> -->
					<view class="delet-modal-confrimbtn" @tap.stop="confrimadd">
						确认
					</view>
				</view>
			</view>
		</u-popup>
		<pagehead>{{bankId?'修改银行卡':'绑定银行卡'}}</pagehead>
		<view class="form-box">
			<view class="form-item">
				<view class="form-item-label">
					开户名
				</view>
				<u--input class="form-item-inner" placeholder="请输入开户名" type="text" customStyle="marginLeft:40rpx"
					border="none" v-model="form.bankusername" readonly>
				</u--input>
			</view>
			<view class="form-item">
				<view class="form-item-label">
					身份证号
				</view>
				<u--input class="form-item-inner" placeholder="请输入身份证号" type="text" customStyle="marginLeft:40rpx"
					border="none" v-model="form.idCard" readonly>
				</u--input>
			</view> 
		</view>
		<view class="form-box">
			<view class="form-item">
				<view class="form-item-label">
					结算卡号
				</view>
				<u--input class="form-item-inner" placeholder="请输入结算卡号" type="number" customStyle="marginLeft:40rpx"
					border="none" v-model="form.bankcardno">
				</u--input>
			</view>
			<!-- <view class="form-item">
				<view class="form-item-label">
					开户行
				</view>
				<u--input class="form-item-inner" placeholder="请输入开户行" type="text" customStyle="marginLeft:40rpx"
					border="none" v-model="form.bankname">
				</u--input>
			</view>
			<view class="form-item">
				<view class="form-item-label">
					开户支行
				</view>
				<u--input class="form-item-inner" placeholder="请输入开户支行" type="text" customStyle="marginLeft:40rpx"
					border="none" v-model="form.branchName">
				</u--input>
			</view> -->
			<view class="upload-box" v-show="!userYsReal">
			<view class="user-image-upload">
				<view class="user-image-upload-title">
					身份证正面
				</view>
				<view class="upload">
					<image v-if="idcardz" :src="idcardzSrc" class="img" />
					<image v-else :src="IMAGE_STATIC+'/userimage/idcradimage.png'" class="img" mode="" @tap.stop="upload('idcardz')" />
					<image :src="IMAGE_STATIC+'/images/close.png'" v-if="idcardz" class="close" @tap.stop="deletePic('idcardz')"/>
				</view>
				<!-- <u-upload :fileList="idcardz" @afterRead="afterRead" @delete="deletePic" name="idcardz"
					:multiple="false" :maxCount="1" width="340rpx" height="200rpx" imageMode="aspectFill">
					<image class="img" src="@/static/user/idcradimage.png" mode="widthFix" />
				</u-upload> -->
			</view>
			<view class="user-image-upload">
				<view class="user-image-upload-tips">
					身份证反面
				</view>
				<view class="upload">
					<image v-if="idcardf" :src="idcardfSrc" class="img" />
					<image v-else :src="IMAGE_STATIC+'/userimage/idcradimage1.png'" class="img" mode="" @tap.stop="upload('idcardf')" />
					<image :src="IMAGE_STATIC+'/images/close.png'" v-if="idcardf" class="close" @tap.stop="deletePic('idcardf')"/>
				</view>
				<!-- <u-upload :fileList="idcardf" name="idcardf" @afterRead="afterRead1" @delete="deletePic1"
					:multiple="false" :maxCount="1" width="340rpx" height="200rpx" imageMode="aspectFill">
					<image class="img" src="@/static/user/idcradimage1.png" mode="widthFix" />
				</u-upload> -->
			</view>
			</view>
			<view class="form-item" v-show="!userYsReal">
				<view class="form-item-label">
					户籍地址省市
				</view>
				<u--input class="form-item-inner" placeholder="请输入户籍地址省市" type="" customStyle="marginLeft:40rpx;marginRight:40rpx;"
					border="none" v-model="form.address">
				</u--input>
			</view>
			<view class="form-item">
				<view class="form-item-label">
					银行预留手机号
				</view>
				<u--input class="form-item-inner" placeholder="请输入银行预留手机号" type="number" customStyle="marginLeft:40rpx;marginRight:40rpx;"
					border="none" v-model="form.account_mobile">
				</u--input>
			</view>
			<view class="form-item">
				<view class="form-item-label">
					图形验证码
				</view>
				<u--input class="form-item-inner" placeholder="请输入图形验证码" type="text" customStyle="marginLeft:40rpx;marginRight:40rpx;"
					border="none" v-model="form.tuCode">
				</u--input>
				<image class="tuCode" :src="img_io" mode="widthFix" @click="getTucode()"></image>
			</view>
			<view class="form-item">
				<view class="form-item-label">
					登录手机号
				</view>
				<view class="form-item-inner">{{usermsg.sys_user_account | conceal(4)}}</view>
			</view>
			<view class="form-item">
				<view class="form-item-label">
					验证码
				</view>
				<u--input class="form-item-inner" placeholder="请输入短信验证码" type="text" customStyle="marginLeft:40rpx;marginRight:40rpx;"
					border="none" v-model="form.code">
				</u--input>
				<view class="form-item-code" @click="sendCode()"><text class="code">{{ remain }}</text></view>
			</view>
			<view class="warn" v-if="!userYsReal">烦请等待1-3分钟提交审核</view>
			<view class="form-item" @tap.stop="addbank">
				<view class="submit">
					提交
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import {compressH5,recursionCompress } from './imgPress'
	export default {
		data() {
			return {
				IMAGE_STATIC: this.$url.assetsPath, // 静态图片地址
				isSend:true,
				remain:'获取验证码',
				img_io:'',
				time:60,
				form:{
					bankusername: '',
					idCard:'',
					bankcardno: '',
					bankname: '',
					branchName:'',
					account_mobile:'' 
				},
				bankId:'',
				addstatus: false,
				usermsg:uni.getStorageSync('usermsg')?uni.getStorageSync('usermsg'):{sys_user_account:''},
				idcardz:'',
				idcardf:'',
				idcardzSrc:'',
				idcardfSrc:'',
				qiniu: '',
				userYsReal:null,
				isShow:true,
			}
		},
		onLoad(options){
			if(options.value1){
				this.bankId = options.value1
				this.getDetail()
				console.log('bankId',this.bankId)
			}
			// this.getUserYsReal()
			this.getTucode()
			this.getQiNiuToken()
		},
		onShow() {
			this.getUserYsReal();
			this.getUserInfo();
		},
		methods: {
			addbank() {
				let that = this;
				// if(!that.form.bankusername){
				// 	return that.$tools.toast('请输入开户名');
				// }
				// if(!that.form.idCard){
				// 	return that.$tools.toast('请输入身份证号');
				// }
				// var pattern = /^[1-9]\d{5}(18|19|20|21|22)?\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|[Xx])$/;
				// if (!pattern.test(that.form.idCard)) {
				// 	return this.$tools.toast('身份证号码有误');
				// } 
				if(!that.form.bankcardno){
					return that.$tools.toast('请输入银行卡号');
				}
				var reg = /^([1-9]{1})(\d{15}|\d{16}|\d{17}|\d{18})$/;
				if(!reg.test(that.form.bankcardno)){
					return that.$tools.toast('请输入正确的银行卡号');
				}
				// if(!that.form.bankname){
				// 	return that.$tools.toast('请输入开户行');
				// }
				// if(!that.form.branchName){
				// 	return that.$tools.toast('请输入开户支行');
				// }
				if(!that.userYsReal && !that.idcardz){
					return that.$tools.toast('请上传身份证正面');
				}
				if(!that.userYsReal && !that.idcardf){
					return that.$tools.toast('请上传身份证反面');
				}
				if(!that.userYsReal && !that.form.address){
					return that.$tools.toast('请输入户籍地址省市');
				}
				if (that.form.account_mobile == '' ) {
					return that.$tools.toast('请输入银行预留手机号');
				}
				if (that.form.account_mobile.length!=11 || !/^((1[0-9])+\d{9})$/.test(that.form.account_mobile)){
					return that.$tools.toast('请输入正确的手机号码！！！');
				}
				if(!that.form.tuCode){
					return that.$tools.toast('请输入图形验证码');
				}
				if(!that.form.code){
					return that.$tools.toast('请输入短信验证码');
				}
				let data = {
					user_account_oper:this.bankId ?'user_account_edit':'user_account_add',
					type:'03',
					account_name: that.form.bankusername,
					// bank_name: that.form.bankname,
					// bank_branch_name:that.form.branchName,
					account: that.form.bankcardno,
					legal_id_card: that.form.idCard,
					account_mobile: that.form.account_mobile,
					sms_code:this.form.code
				}
				if(!that.userYsReal){
					let legal_card_photo = [that.idcardz,that.idcardf]
					data['legal_card_photo'] = legal_card_photo.join(',')
					let sign_back_url
					// #ifdef APP-PLUS || H5
					 sign_back_url=that.$url.urlPath + '/#/pages/bank/bank'
					// #endif
					// #ifdef APP-PLUS
					sign_back_url='/pages/bank/bank'
					// #endif
					// #ifdef MP-WEIXIN
					let path = 'pagesMain/index/index'
					let query = ""
					let ENV_VERSION = ''
					sign_back_url = `weixin://dl/business/?appid=wx8680e48d44da9d29&path=${path}&query=${query}&env_version=${ENV_VERSION}`
					// #endif
					data['sign_back_url'] = sign_back_url
					data['address'] = that.form.address
				}
				if(this.bankId){
					data['account_id'] = this.bankId
				}
				console.log('data',data)
				uni.showLoading({
						mask: true,
						title: '提交中'
				});
				that.$Ajax('/api/user/account/updateUserAccount',data,res => {
					uni.hideLoading();
					if (res.success) {
						that.$tools.toastJump(res.msg,'/pages/bank/bank');
						// if(res.data){
						// 	// that.goSing(res.data)
						// }else{
						// 	that.$tools.toastBack(res.msg,1);
						// }
						// that.addstatus = true;
					}
				},err=>{
					console.log('err',err)
					that.$tools.toast('提交失败')
					uni.hideLoading();
				})
			},
			// 去签约
			goSing(url){
				console.log('跳转')
				// #ifdef H5
				location.href = url
				// window.open(url)
				// #endif
				// #ifdef MP-WEIXIN
				uni.setStorageSync('singUrl',encodeURIComponent(url))
				this.$tools.jump('/pages/service/service','','','/pages/bank/bank')
				// #endif
				// #ifdef APP-PLUS
				this.$tools.jump('/pages/service/service',url,'','/pages/bank/bank')
				// #endif
			},
			// 删除
			deletePic(key) {
				this[key] = ''
			},
			// 上传图片
			upload(key){
				const that = this
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
					success: res => {
						console.log(res)
						// 获取文件的临时路径
						let avatar = res.tempFilePaths[0];
						let files = res.tempFiles[0]
						const fileSize = files.size;
						console.log('fileSize',fileSize)
						if(fileSize/1024/1024 >20){
							return that.$tools.toast('请上传20M以内的图片')
						}
						uni.showLoading({
								mask: true,
						});
					// 判断图片大小是否超过200KB
					if (fileSize > 20 * 1024) {
						//#ifdef H5
						//h5压缩图片
						const targetSizeKB = 150; // 设置目标文件大小，单位为KB，根据需求调整
						compressH5(files,targetSizeKB).then(file => {
							console.log('file 222 = ', file)
							that.uploadCompressedImage(file,key);
							}).catch(err => {
								console.log('catch', err)
								uni.hideLoading();
						})
					//#endif

					//#ifdef APP-PLUS || MP-WEIXIN
					// 如果超过200KB，进行压缩
				 // 小程序
				 recursionCompress(files.path, 1, false, (compressedFilePath) => {
							// console.log("压缩成功，压缩后图片路径：", compressedFilePath);
							 that.uploadCompressedImage(compressedFilePath,key);
						
					}, (err) => {
							console.error("压缩失败：", err);
							uni.hideLoading();
					})
					//#endif
					} else {
							// 如果未超过200KB，直接上传原图
							that.uploadCompressedImage(avatar,key);
					}
				},
				fail: (error) => {
					console.log(error);
					that.$tools.toast('上传图片接口调用失败')
					uni.hideLoading();
				},
			})
					
			},
			// 压缩上传
			uploadCompressedImage(avatar,key){
					const that = this
					// let avatar = res.tempFiles;
					let KeySrc = key+'Src'
					console.log(key,avatar)
					that[KeySrc] = avatar;
					that.$set(that,KeySrc,avatar)
					let now_time = new Date().getTime();
					uni.uploadFile({
						url: 'https://up-z2.qiniup.com', 
						filePath: avatar,
						name: 'file',
						formData: {
							// 'key': now_time,
							'token': that.qiniu.qiniu_token,
						},
						success: (uploadFileRes) => {
							let uploadImgUrl = JSON.parse(uploadFileRes.data).key;
							// let backUrl = that.qiniu.qiniu_domain + '/' +uploadImgUrl;
							let backUrl = uploadImgUrl;
							that[key] = backUrl;
							that.$set(that,key,backUrl)
							console.log(key,this[key])
							uni.hideLoading();
						},
						fail: (error) => {
							console.log(error);
							uni.hideLoading();
						},
						complete: () => {
							setTimeout(function() {
								uni.hideLoading();
							}, 250);
						},
					});
			},
			// 获取七牛云token
			getQiNiuToken() {
				let that = this;
				that.$Ajax('/api/common/qiniu/getQiNiuToken', {}, res => {
					if(res.success){
						that.qiniu =  res.data;
					}
				}, err => {})
			},
			// 发送验证码
			sendCode() {
				if (this.form.account_mobile == '' ) {
					return this.$tools.toast('请输入银行预留手机号');
				}
				if (this.form.account_mobile.length!=11 || !/^((1[0-9])+\d{9})$/.test(this.form.account_mobile)){
					return this.$tools.toast('请输入正确的手机号码！！！');
				}
				if (this.form.tuCode == '') {
					return this.$tools.toast('请输入图形验证码');
				}
				if(this.isSend == true){
					uni.showLoading({
						title: '发送中',
						mask: true
					});
					var data = {
						user_account: this.form.account_mobile,
						bus_type: 'FrontSetUserAccount',
						img_id: this.img_id,
						img_code: this.form.tuCode,
					};
					console.log("data：",data);
					this.$Ajax('/api/common/smsCode/sendSmsCodeOnly',
					data,
					res => {
							this.$tools.toast('短信发送成功')
							this.isSend = false;
							this.remain = this.time + 's';
							this.uuid = res.data
							this.timer = setInterval(() => {
								this.time--;
								this.remain = this.time + 's';
								if (this.time == 0) {
									clearInterval(this.timer);
									this.remain = '重新获取';
									(this.isSend = true), (this.time = 60);
								}
							}, 1000);
						}
					)
					uni.hideLoading();
				}
			},
			// 获取图形验证码
			getTucode() {
				const data = {
					interface_type: 'createImgCode'
				}
				this.$Ajax('/api/common/imgCode/createImgCode', data, res => {
					// console.log('data',res)
					if (res.success) {
						this.img_id = res.data.img_id
						this.img_io = res.data.img_io
					}
				})
			},
			// 查询易税实名信息
			getUserYsReal() {
				let that = this;
				that.$Ajax('/api/user/info/getUserYsReal', {}, res => {
					if(res.success){
						// that.userYsReal =  res.data.userYsReal;
						console.log('userYsReal',that.userYsReal)
					}
				}, err => {})
			},
			// 获取详情
			getDetail(){
      let that = this;
      const data = {
        account_id: this.bankId
      }
      console.log('data',data)
      that.$Ajax('/api/user/account/getUserAccountById',data,
      res => {
        if(res.success){
					that.form.bankusername=res.data.userAccount.account_name;
					that.form.bankcardno=res.data.userAccount.account 
					that.form.bankname=res.data.userAccount.bank_name
					that.form.branchName=res.data.userAccount.bank_branch_name
					that.form.idCard=res.data.userAccount.legal_id_card
        }
      }, err => {
        console.log(err);
      })
			},
			// 查询用户信息
			getUserInfo() {
				this.$Ajax('/api/user/info/getRealUserInfo', {}, res => {
					if(res.success){
						this.usermsg = res.data.userInfo
						uni.setStorageSync('usermsg', this.usermsg);
						console.log('usermsg',this.usermsg);
						if(this.usermsg.real_name){
							this.form.bankusername = this.usermsg.real_name
							this.form.idCard = this.usermsg.id_card
						}else{
							this.$tools.toastJump('请先实名','/pages/setup/editUserInfo')
						}
					}
				}, err => {uni.hideLoading();})
				uni.hideLoading();
			},
			closemodal() {
				this.addstatus = false;
			},
			confrimadd(){
				this.$tools.back(1);
			}
		}
	}
</script>

<style scoped lang="scss">
@import '@/common/scss/operate';
.upload-box{
	// @include flexBetween;
	margin: 40rpx auto;
	.upload{
		width: 492rpx;
		height: 300rpx;
		position: relative;
	}
	.close{
		position: absolute;
		top: 0;
		right: 0;
		width: 40rpx;
		height: 40rpx;
	}
	.img{
		width: 492rpx;
		height: 100%;
	}
}
.warn{
	color: red;
	font-size: 14px;
}
</style>
